package com.edu.chongdian.viewmodels;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.widget.Toast;

import com.edu.chongdian.MainActivity;
import com.edu.chongdian.View.SignInActivity;
import com.edu.chongdian.databinding.ActivityLoginBinding;
import com.edu.chongdian.model.User;

import cn.leancloud.LCUser;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class LoginViewModel{
    public User user;
    private Context context;
    public SharedPreferences sp;

    public LoginViewModel(Context context,ActivityLoginBinding binding){
        user=new User();
        this.context=context;
        sp = context.getSharedPreferences("login_info",context.MODE_PRIVATE);
        binding.setViewModel(this);
    }

    public void login() {
        String accountValue = user.username.get();
        String passwordValue = user.password.get();
        if (TextUtils.isEmpty(accountValue) || TextUtils.isEmpty(passwordValue)) {
            Toast.makeText(context, "账号密码不为空", Toast.LENGTH_SHORT).show();
            return;
        }
        LCUser.logIn(accountValue, passwordValue).subscribe(new Observer<LCUser>() {
            public void onSubscribe(Disposable disposable) {}
            public void onNext(LCUser user) {
                // 登录成功
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("account", accountValue.trim());
                editor.putString("password", passwordValue.trim());
                editor.apply();
                Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();
                context.startActivity(new Intent(context, MainActivity.class));
                // 销毁当前 Activity
                if (context instanceof Activity) {
                    ((Activity) context).finish();
                }
            }
            public void onError(Throwable throwable) {
                // 登录失败（可能是密码错误）
                Toast.makeText(context, "账号或密码错误", Toast.LENGTH_SHORT).show();
            }
            public void onComplete() {}
        });
      /*  if (accountValue.equals("admin") && passwordValue.equals("123456")) {

            SharedPreferences.Editor editor = sp.edit();
            editor.putString("account", accountValue.trim());
            editor.putString("password", passwordValue.trim());
            editor.apply();
            Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();
            context.startActivity(new Intent(context, MainActivity.class));
            // 销毁当前 Activity
            if (context instanceof Activity) {
                ((Activity) context).finish();
            }
        } else {
            Toast.makeText(context, "账号或密码错误", Toast.LENGTH_SHORT).show();
        }*/
    }
    public void signIn(){
        context.startActivity(new Intent(context, SignInActivity.class));
    }

}
